// @ts-nocheck
import axios, { AxiosInstance, AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios';
import { DateRangePicker, MessagePlugin } from 'tdesign-vue-next';
import { setAuthorization, getHeardToken, getHeardXtoken, setMd5Info, removeAuthorization } from './utils';
import router from '../router/index';
import { outLogin } from '@/utils/minxin';

// 是否正在刷新的标记
let isRefreshing = false;
// 重试队列，每一项将是一个待执行的函数形式
let requests = [];
interface Result {
  code: number;
  msg: string;
  data?: any;
  errors?: any; 
  extras?: any;
  statusCode: number;
  succeeded: boolean;
  timestamp: number;
}
type PersonHeard = {
  'access-token': string;
  'x-access-token': string;
  'content-type': string;
  environment: string;
};
// 请求响应参数，包含data
interface ResultData<T = any> extends Result {
  data?: T;
}
const apiUrl = {};
if (import.meta.env.MODE === 'development') {
  //开发环境下的执行操作
  //生产环境下的执行操作 
 
  apiUrl['file'] = '//t-api.youxinjiyi.com/file/';
  apiUrl['message'] = '//t-api.youxinjiyi.com/message/';
  apiUrl['sys'] = '//t-api.youxinjiyi.com/sys/'; 
  apiUrl['api'] = '//t-api.youxinjiyi.com/curating/'; 
  apiUrl['ai'] = '//t-api.youxinjiyi.com/ai/';
} else {
  //生产环境下的执行操作 
  apiUrl['file'] = '//fileapi.jiyi.show/';
  apiUrl['message'] = '//messageapi.jiyi.show/';
  apiUrl['sys'] = '//sysapi.jiyi.show/'; 
  apiUrl['api'] = '//api.jiyi.show/'; 
  apiUrl['ai'] = '//www.jiyi.show/ai/';
}
const URL: string = import.meta.env.MODE === 'development' ? '//t-api.youxinjiyi.com/user/' : '//userapi.jiyi.show/';
//const URL: string = import.meta.env.MODE === 'development' ? 'http://t-user.api.jiyi.show/' : '//user.api.jiyi.show/';
enum RequestEnums {
  TIMEOUT = 200000, 
  OVERDUE = 401, // 登录失效
  FAIL = 999, // 请求失败 
  SUCCESS = 200, // 请求成功
}
let settimer=null
const config = {
  // 默认地址
  baseURL: URL as string,
  // 设置超时时间
  timeout: RequestEnums.TIMEOUT as number,
  // 跨域时候允许携带凭证
  withCredentials: false,
};

class RequestHttp {
  // 定义成员变量并指定类型
  service: AxiosInstance;
  public constructor(config: AxiosRequestConfig) {
    // 实例化axios

    this.service = axios.create(config);
    /**
     * 请求拦截器
     * 客户端发送请求 -> [请求拦截器] -> 服务器
     * token校验(JWT) : 接受服务器返回的token,存储到vuex/pinia/本地储存当中
     */

    this.service.interceptors.request.use(
      (config: any) => {
        //AxiosRequestConfig
        const token = getHeardToken() || '';
        const Xtoken = getHeardXtoken() || '';  
        const Hwkeys = setMd5Info();
        config.responseType = config.url.indexOf('api/exhibition/export') !== -1 ? 'blob' : '';
        var configs: AxiosRequestConfig = config;
        if (configs.url.indexOf('base64') !== -1 || configs.url.indexOf('/cloud/') !== -1) {
          configs.baseURL = apiUrl.file;
        }
        if (configs.url.indexOf('code/send') !== -1) {
          configs.baseURL = apiUrl.message;
        }
        if (
          configs.url.indexOf('/dict') !== -1 ||
          configs.url.indexOf('recommend/list') !== -1 ||
          configs.url.indexOf('content') !== -1 ||
          configs.url.indexOf('notice') !== -1 ||
          configs.url.indexOf('banner') !== -1
        ) {
          configs.baseURL = apiUrl.sys;
        }
        if (
          configs.url.indexOf('showpiece') !== -1 ||
          configs.url.indexOf('curator') !== -1 ||
          configs.url.indexOf('company') !== -1 ||
          configs.url.indexOf('browse') !== -1 ||
          configs.url.indexOf('label') !== -1 ||
          configs.url.indexOf('project') !== -1 ||
          configs.url.indexOf('exhibition') !== -1 ||
          configs.url.indexOf('goods') !== -1 ||
          configs.url.indexOf('folder') !== -1 ||
          configs.url.indexOf('investigation') !== -1 ||
          configs.url.indexOf('api/interact') !== -1 ||
          configs.url.indexOf('template') !== -1 || 
          configs.url.indexOf('api/comment') !== -1 || 
          configs.url.indexOf('api/tag/') !== -1 ||
          configs.url.indexOf('/invite') !== -1
        ) {
          configs.baseURL = apiUrl.api;
        }
        if (configs.url.indexOf('api/ai') !== -1) {
          configs.baseURL = apiUrl.ai;
        }
        if (configs.url.indexOf('api/wei-xin') !== -1) {
          configs.baseURL = apiUrl.ai;
        }

        let SMSCode = configs.data?.HW_CE_SMSCode;
        // console.log(configs.data.HW_CE_SMSCode);
        return {
          ...configs,
          headers: {
            'Content-Type':  
              config.url.indexOf('api/exhibition/export') !== -1 ? 'blob' : 'application/json;charset=utf-8',
            // 'Access-Control-Allow-Origin': '*',
            Authorization: token,
            'X-Authorization': Xtoken, // 请求头中携带token信息
            hwappkey: Hwkeys.HWAppKey,
            hwappsecret: Hwkeys.HWAppSecret,
            hwappid: Hwkeys.HWAppId,
            'hwrequest-timestamp': Hwkeys.HWRequestTimeStamp,
            'hw-message-code': SMSCode,
            responseType: config.url.indexOf('api/exhibition/export') !== -1 ? 'Blob' : '',
          },
        };
      },
      (error: AxiosError) => {
        // 请求报错
        Promise.reject(error);
      },
    );
    /**
     * 响应拦截器
     * 服务器换返回信息 -> [拦截统一处理] -> 客户端JS获取到信息
     */

    this.service.interceptors.response.use(
      (response: AxiosResponse) => {
        let heardInfo: any = response.headers;
        setAuthorization(heardInfo);

        const { data, config } = response; // 解构
        // console.log(config.url, '链接');
        if (data.statusCode !== 200 && config.url.indexOf('api/exhibition/export') === -1) {
          this.handleCode(data.statusCode, data.errors);
          Promise.reject(data);
          // return Promise.reject(data);
          // MessagePlugin.error({ content: data.errors });
        }

        if (data.statusCode == 401 && configs.url.indexOf('/login') == -1) {
          this.handleCode(data.statusCode, data.errors);
          Promise.reject(data);
          // return Promise.reject(data);
          // MessagePlugin.error({ content: data.errors });
        } else if (data.statusCode == 403 && configs.url.indexOf('/login') == -1) {
          this.handleCode(data.statusCode, data.errors);
          Promise.reject(data);
        } else if (data.statusCode == 401 && configs.url.indexOf('/login') !== -1) {
          this.handleCode(data.statusCode, data.errors);
          Promise.reject(data);
        }
        if (data && config.url.indexOf('api/exhibition/export') !== -1) {
          console.log(data, '头部');
          Promise.reject(data);
        }
        // if (data.statusCode === RequestEnums.OVERDUE) {
        //   //
        //   // return Promise.reject(data);
        // } // 全局错误信息拦截（防止下载文件得时候返回数据流，没有code，直接报错）
        // if (data.statusCode && data.statusCode !== RequestEnums.SUCCESS) {
        //   MessagePlugin.error({ content: data.errors }); // 此处也可以使用组件提示报错信息
        //   return Promise.reject(data);
        // }

        return data;
      },
      (error: AxiosError) => {
        const { response } = error;
        if (response) {
          this.handleCode(response.status);

          if (response.status == 401) {
            router.push({ path: '/login' });
            // let url = window.location.href;
            // router.push({ path: '/login', query: { redirect: url } });
          }
        }
        if (!window.navigator.onLine) {
          MessagePlugin.error('链接失败'); //链接失败 // 可以跳转到错误页面，也可以不做操作 // return router.replace({ //   path: '/404' // });
        }
      },
    );
  }
  handleCode(code: number, err?: any): void {
    let url = window.location.href;
    let redirectUrl =
      import.meta.env.MODE === 'development'
        ? 'https://t-www.youxinjiyi.com/login?redirect=' + url
        : 'https://www.jiyi.show/login?redirect=' + url;
        clearTimeout(settimer)
        settimer=setTimeout(() => {
          switch (code) {
            case 403:
              MessagePlugin.error('登录过期');
              removeAuthorization();
              // router.push({ path: '/login' });
              outLogin(redirectUrl);
              break; 
            case 401:
              removeAuthorization();
              MessagePlugin.error('登录过期');
              // router.push({ path: '/login' });
              // router.push({ path: '/login' });
      
              outLogin(redirectUrl);
              break;
      
            default:
              if (typeof err === 'string') {
                MessagePlugin.error(err);
              } else {
                MessagePlugin.error(JSON.stringify(err));
              }
              break;
          }
        }, 200);
    
  }
  // 常用方法封装
  get<T>(url: string, params?: object): Promise<ResultData<T>> {
    return this.service.get(url, { params });
  }
  post<T>(url: string, params?: object): Promise<ResultData<T>> {
    return this.service.post(url, params);
  }
  patch<T>(url: string, params?: object): Promise<ResultData<T>> {
    return this.service.patch(url, params);
  }
  put<T>(url: string, params?: object): Promise<ResultData<T>> {
    return this.service.put(url, params);
  }
  delete<T>(url: string, params?: object): Promise<ResultData<T>> {
    return this.service.delete(url, { params });
  }
  deletes<T>(url: string, params?: any): Promise<ResultData<T>> {
    return this.service.delete(url, { data: params });
  }
}

// 导出一个实例对象
export default new RequestHttp(config);
